<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <!-- 申请标题搜索项 -->
      <el-form-item label="申请标题" prop="applicationTitle">
        <el-input
          v-model="queryParams.applicationTitle"
          placeholder="请输入申请标题"
          clearable
          @keyup.enter="handleQuery"
          @clear="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <!-- 申请类型搜索项 -->
      <el-form-item label="申请类型" prop="applicationType">
        <el-select
          v-model="queryParams.applicationType"
          placeholder="请选择申请类型"
          clearable
          @clear="handleQuery"
          class="!w-200px"
        >
          <el-option label="ETL" value="1" />
          <el-option label="数据集" value="2" />
          <el-option label="数据接口" value="3" />
        </el-select>
      </el-form-item>

      <!-- 申请状态搜索项 -->
      <el-form-item label="申请状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择申请状态"
          clearable
          class="!w-200px"
          @clear="handleQuery"
        >
          <el-option label="已提交" value="1" />
          <el-option label="审核中" value="2" />
          <el-option label="审核不通过" value="3" />
          <el-option label="审核通过" value="4" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column label="序号" width="55" align="center">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="申请标题" align="center" prop="applicationTitle" />
      <el-table-column label="申请类型" align="center" prop="applicationType">
        <template #default="scope">
          <span v-if="scope.row.applicationType === '1'">ETL</span>
          <span v-else-if="scope.row.applicationType === '2'">数据集</span>
          <span v-else-if="scope.row.applicationType === '3'">数据接口</span>
          <span v-else>未知类型</span>
        </template>
      </el-table-column>
      <el-table-column label="申请原因" align="center" prop="applicationReason" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span v-if="scope.row.status === '1'" class="text-green-500">已提交</span>
          <span v-else-if="scope.row.status === '2'" class="text-red-500">审核中</span>
          <span v-else-if="scope.row.status === '3'" class="text-green-500">审核不通过</span>
          <span v-else-if="scope.row.status === '4'" class="text-red-500">审核通过</span>
          <span v-else>未知状态</span>
        </template>
      </el-table-column>
      <el-table-column
        label="提交时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="120px">
        <template #default="scope">
          <el-button type="primary" link @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 详情弹窗 -->
  <el-dialog v-model="detailDialogVisible" title="审批详情" width="800px" align-center>
    <div
      v-loading="detailLoading"
      style="display: flex; align-items: center; flex-direction: column"
    >
      <el-table row-key="id" :data="detailPagedList" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="审核结果" align="center" prop="auditResult">
          <template #default="scope">
            <span v-if="scope.row.auditResult === '0'">待审核</span>
            <span v-else-if="scope.row.auditResult === '1'">审核通过</span>
            <span v-else-if="scope.row.auditResult === '2'">审核不通过</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审核账号" align="center" prop="auditor" />
        <el-table-column label="完成状态" align="center" prop="completeStatus">
          <template #default="scope">
            <span v-if="scope.row.currentNodeCode === 'NOTIFY'">-</span>
            <span v-if="scope.row.completeStatus === '0' && scope.row.currentNodeCode !== 'NOTIFY'"
              >待完成</span
            >
            <span v-else-if="scope.row.completeStatus === '1'">已完成</span>
          </template>
        </el-table-column>
        <el-table-column label="当前节点" align="center" prop="currentNodeCode">
          <template #default="scope">
            <span v-if="scope.row.currentNodeCode === 'LEFT_1'">信息中心经办人审核</span>
            <span v-else-if="scope.row.currentNodeCode === 'LEFT_2'">信息中心审核人审核</span>
            <span v-else-if="scope.row.currentNodeCode === 'LEFT_3'">信息中心分管领导审核</span>
            <span v-else-if="scope.row.currentNodeCode === 'RIGHT'">数源单位审核</span>
            <span v-else-if="scope.row.currentNodeCode === 'DEPT_SELECT'">科信处选择审核人</span>
            <span v-else-if="scope.row.currentNodeCode === 'DEPT_AUDIT'">科信处多人审核</span>
            <span v-else-if="scope.row.currentNodeCode === 'LEADER_AUDIT'">科信处领导审核</span>
            <span v-else-if="scope.row.currentNodeCode === 'NOTIFY'">信息中心通知</span>
          </template>
        </el-table-column>

        <el-table-column label="完成时间" align="center" prop="completeTime">
          <template #default="scope">
            {{ scope.row.completeTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹窗内分页 -->
      <Pagination
        v-if="detailTotal > 0"
        :total="detailTotal"
        v-model:page="detailPageNo"
        v-model:limit="detailPageSize"
        @pagination="handleDetailPagination"
        class="mt-4"
      />
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import { getApprovalRecordList, getApprovalRecordDetail } from '@/api/business/approval'
import { onMounted, ref, reactive, computed } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'

/** 审批记录列表 */
defineOptions({ name: 'ApprovalRecordList' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryFormRef = ref() // 搜索的表单

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  applicationTitle: undefined,
  applicationType: undefined,
  status: undefined
})

// 详情弹窗相关
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const detailList = ref([]) // 完整的详情数据
const detailTotal = ref(0) // 详情数据总数
const detailPageNo = ref(1) // 详情当前页码
const detailPageSize = ref(10) // 详情每页条数
const currentApplicationId = ref(null) // 当前查看详情的申请ID

// 分页后的详情数据
const detailPagedList = computed(() => {
  const start = (detailPageNo.value - 1) * detailPageSize.value
  const end = start + detailPageSize.value
  return detailList.value.slice(start, end)
})

/** 格式化日期范围 */
const formatDateRange = (start?: string, end?: string) => {
  // 提取年月日部分的辅助函数
  const extractDatePart = (dateString?: string) => {
    if (!dateString) return ''
    // 检查是否包含空格，提取年月日部分
    const datePart = dateString.split(' ')[0]
    return datePart
  }

  if (!start) return ''
  if (!end) return extractDatePart(start)
  return `${extractDatePart(start)} - ${extractDatePart(end)}`
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getApprovalRecordList(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    message.error('获取审批记录失败，请重试')
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  handleQuery()
}

/** 详情按钮操作 */
const handleDetail = async (row: any) => {
  // 重置详情弹窗的分页状态
  detailPageNo.value = 1
  detailPageSize.value = 10
  currentApplicationId.value = row.id

  try {
    detailLoading.value = true
    const data = await getApprovalRecordDetail({ applicationId: row.id })
    detailList.value = data.list
    detailTotal.value = data.total
    detailDialogVisible.value = true
  } catch (error) {
    message.error('获取审批记录详情失败，请重试')
  } finally {
    detailLoading.value = false
  }
}

/** 详情弹窗分页处理 */
const handleDetailPagination = () => {
  // 分页变化时会自动更新detailPagedList，这里不需要额外操作
}

/** 初始化 **/
onMounted(async () => {
  getList()
})
</script>

<style scoped>
/* 可以添加一些自定义样式 */
</style>
